package com.sanjin.domain;

import com.alibaba.fastjson2.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private UmsSysUser user;

    private String token;

    //存储权限列表
    private List<String> permissions;

    // 构造函数
    public LoginUser(UmsSysUser user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    // 构造函数
    public LoginUser(UmsSysUser user, List<String> permissions,String token) {
        this.user = user;
        this.permissions = permissions;
        this.token = token;
    }

    //存储security的权限信息集合
    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(authorities!=null){
            return authorities;
        }
        //把permissions字符串的权限信息转换为GrantedAuthority
        return permissions.stream().map(SimpleGrantedAuthority::new).toList();
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    //判断账户是否过期
    @Override
    public boolean isAccountNonExpired() {
        return user.getStatus() == 0;
    }

    //判断账户是否被锁定
    @Override
    public boolean isAccountNonLocked() {
        return user.getStatus() == 0;
    }

    //判断用户凭证是否过期
    @Override
    public boolean isCredentialsNonExpired() {
        return user.getStatus() == 0;
    }

    //判断账户是否启用
    @Override
    public boolean isEnabled() {
        return user.getStatus() == 0;
    }
}
